package org.git.movie.videojiexi.service.impl;


import org.git.movie.videojiexi.common.util.VideoHelper;
import org.git.movie.videojiexi.enums.VideoChannel;
import org.git.movie.videojiexi.model.VideoModel;
import org.git.movie.videojiexi.service.VideoService;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**  
* @comment
* @author tanran 
* @date 2019年6月14日  
* @version 1.0  
*/
@Service("DouyinServiceImpl")
public class DouyinServiceImpl implements VideoService {


	private static Logger log = LoggerFactory.getLogger(DouyinServiceImpl.class);

	Pattern patternCompile = Pattern.compile("(?<=playAddr: \")https?://.+(?=\",)");

	@Override
	public VideoModel parseUrl(String url, String userAgent) throws Exception {
		//过滤链接，获取http连接地址
		String finalUrl = VideoHelper.decodeHttpUrl(url);

		//1.利用Jsoup抓取抖音链接
		//抓取抖音网页
		String htmls = Jsoup.connect(finalUrl).ignoreContentType(true).execute().body();
		//System.out.println(htmls); //做测试时使用

		//2.利用正则匹配可以抖音下载链接
		//playAddr: "https://aweme.snssdk.com/aweme/v1/playwm/?video_id=v0200ffc0000bfil6o4mavffbmroeo80&line=0",
		//具体匹配内容格式：「https://aweme.snssdk.com/aweme/...line=0」

		//利用Pattern.compile("正则条件").matcher("匹配的字符串对象")方法可以将需要匹配的字段进行匹配封装 返回一个封装了匹配的字符串Matcher对象

		//3.匹配后封装成Matcher对象
		Matcher m = patternCompile.matcher(htmls);

		//4.①利用Matcher中的group方法获取匹配的特定字符串 ②利用String的replace方法替换特定字符,得到抖音的去水印链接
		String matchUrl ="";
		while(m.find()) {
			matchUrl = m.group(0).replaceAll("playwm", "play");
		}
		VideoModel rep = new VideoModel();
		rep.setChannel(VideoChannel.DOUYIN);
		rep.setPlayAddr(matchUrl);

		return rep;
	}


	/**
	 * 抖音视频解析  http://freejx.cn/
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		System.out.println(new DouyinServiceImpl().parseUrl("https://v.douyin.com/JkngUeD/","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36"));
	}
}
